<template>
  <el-dialog
    :visible="tagAddStatus"
    :title="tagData ? '修改标签' : '新增标签'"
    @close="btnCancel"
    width="400px"
  >
    <el-form ref="tagForm" :model="tagForm" :rules="rules" label-width="80px">
      <el-form-item label="所属学科" prop="subjectID" v-if="!subjectId">
        <el-select
          v-model="tagForm.subjectID"
          placeholder="请选择"
          style="width: 80%"
        >
          <el-option
            v-for="item in subjectList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录名称" prop="tagName">
        <el-input
          v-model="tagForm.tagName"
          style="width: 80%"
          placeholder="请输入目录名称"
      /></el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-button type="primary" size="small" @click="btnOK">确定</el-button>
      <el-button size="small" @click="btnCancel">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { simple } from '@/api/hmmm/subjects.js'
import { add, update } from '@/api/hmmm/tags.js'
export default {
  props: {
    tagAddStatus: {
      type: Boolean,
      default: false
    },
    subjectId: {
      type: String,
      default: null
    },
    tagData: {
      type: Object
    }
  },
  data () {
    return {
      tagForm: {
        subjectID: '',
        tagName: ''
      },
      rules: {
        subjectID: [{ required: true, message: '所属学科不能为空', trigger: 'change' }],
        tagName: [{ required: true, message: '目录名称不能为空', trigger: 'blur' }]
      },
      subjectList: []
    }
  },
  created () {
    simple().then((res) => {
      this.subjectList = res.data
    })
    if (this.subjectId) {
      this.tagForm.subjectID = parseInt(this.subjectId)
    } else if (this.tagData) {
      this.tagForm.subjectID = parseInt(this.tagData.subjectID)
      this.tagForm.tagName = this.tagData.tagName
    }
  },
  methods: {
    btnOK () {
      this.$refs.tagForm.validate()
        .then(() => {
          if (this.tagData) {
            update({ id: this.tagData.id, ...this.tagForm })
          } else add(this.tagForm)
        }).then(() => {
          this.$message.success(this.tagData ? '修改标签成功' : '新增标签成功')
          this.$emit('refreshDataList')
          this.btnCancel()
        }).catch((err) => {
          console.log(err)
          this.$message.error(err)
        })
    },
    btnCancel () {
      this.$emit('update:tagAddStatus', false)
      this.$emit('update:tagData', null)
    }
  }
}
</script>

<style scoped lang='scss'></style>
